package com.xuelang.pipeline.artifact.client.common.util;

import cn.hutool.core.util.ObjectUtil;
import com.xuelang.pipeline.artifact.client.common.exception.BizException;

import java.util.HashMap;
import java.util.Map;

/**
 * jwtUtils
 *
 * @author xiwen.zxg
 * @since 2024/5/17
 */
public class JwtUtil {

    private static final ThreadLocal<Map<String, String>> threadLocal = new ThreadLocal<>();
    /**
     * AES 16位密钥
     */
    protected static final byte[] KEY = "8#$45%812%53Tr68".getBytes();

    protected static final String ISSUER = "zhang";

    public static final String THREAD_PHONE = "phone";

    public static final String THREAD_LOGIN_CHN = "loginChn";

    public static final int EXPIRES_WEEK = 1;

    /**
     * ThreadLocal获取手机号码
     */
    public static String getPhone() {
        Map<String, String> threadMap = threadLocal.get();
        if (ObjectUtil.isNotNull(threadMap)) {
            return threadMap.get(THREAD_PHONE);
        } else {
            throw new BizException("获取用户信息失败!");
        }
    }

    public static String getPhoneNullable() {
        Map<String, String> threadMap = threadLocal.get();
        if (ObjectUtil.isNotNull(threadMap)) {
            return threadMap.get(THREAD_PHONE);
        } else {
            return "";
        }
    }

    /**
     * ThreadLocal获取渠道号
     */
    public static String getThreadLoginChn() {
        Map<String, String> threadMap = threadLocal.get();
        if (ObjectUtil.isNotNull(threadMap)) {
            return threadMap.get(THREAD_LOGIN_CHN);
        } else {
            throw new BizException("获取用户信息失败!");
        }
    }

    /**
     * ThreadLocal设置数据
     */
    public static void setDataToThreadLocal(String phone, String loginChn) {
        Map<String, String> threadMap = new HashMap<>(16);
        threadMap.put(THREAD_PHONE, phone);
        threadMap.put(THREAD_LOGIN_CHN, loginChn);
        threadLocal.set(threadMap);
    }

    /**
     * 每次请求完成 清除ThreadLocal
     */
    public static void removeThreadLocal() {
        threadLocal.remove();
    }

    /**
     * mdc 获取手机号记录日志
     *
     * @param token token
     * @return phone
     */
    public static String verifyGetPhoneForMdc(String token) {
        String phone = "";
        try {
            phone = WebJwtUtil.getPhone(token);
        } catch (Exception ignored) {
        }
        return phone;
    }


    /**
     * 验证token 是否可用
     *
     * @param token token
     */
    public static void verifyTokenForBoth(String token) {
        WebJwtUtil.verifyToken(token);
        String phone = WebJwtUtil.getPhone(token);
        setDataToThreadLocal(phone, "00");
    }
}
